//
//  InnerWKWebViewController.m
//  Unity-iPhone
//
//  Created by Karl on 2017/3/28.
//
//

#import "InnerWKWebViewController.h"
#import <WebKit/WebKit.h>

@interface InnerWKWebViewController ()<WKNavigationDelegate>

@end

@implementation InnerWKWebViewController{
    NSString *_url;
    WKWebView *_webView;
    UIProgressView *_progressView;
    UIToolbar *_bar;
    UIButton *_bkBtn;
    UIButton *_fwBtn;
//    UIButton *_rfBtn;
}

- (instancetype)initWithUrl:(NSString *)url{
    self=  [super init];
    if (self) {
        _url = url;
    }
    return self;
}

- (void)dealloc{
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_webView removeObserver:self forKeyPath:@"title"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor  =[UIColor whiteColor];
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithTitle:Babel(@"back") style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    [self.navigationItem setLeftBarButtonItem:back];
    
    UIBarButtonItem *refresh = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(webRefreshAction:)];
    [self.navigationItem setRightBarButtonItem:refresh];
    
    
    _webView = [[WKWebView alloc] initWithFrame:CGRectZero];
    _webView.navigationDelegate = self;
    [self.view addSubview:_webView];
    
    _progressView = [[UIProgressView alloc] initWithFrame:CGRectZero];
    _progressView.alpha = 0;
    [self.navigationController.navigationBar addSubview:_progressView];
    
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    [_webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:_url]]];
//    [_webView.scrollView setContentInset:UIEdgeInsetsMake(0, 0, 40, 0)];
    [_webView setAllowsBackForwardNavigationGestures:YES];
    
    _bar = [[UIToolbar alloc] initWithFrame:CGRectZero];
    [_bar setBarStyle:UIBarStyleDefault];
    [self.view addSubview:_bar];
    
    _bkBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_bkBtn setTitle:@"<" forState:UIControlStateNormal];
    [_bkBtn addTarget:self action:@selector(webBackAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bkBtn setEnabled:NO];
    [_bar addSubview:_bkBtn];
    
    _fwBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_fwBtn setTitle:@">" forState:UIControlStateNormal];
    [_fwBtn addTarget:self action:@selector(webForwardAction:) forControlEvents:UIControlEventTouchUpInside];
    [_fwBtn setEnabled:NO];
    [_bar addSubview:_fwBtn];
    
    
    [_bar setHidden:YES];
//    _rfBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//    [_rfBtn setTitle:Babel(@"refresh") forState:UIControlStateNormal];
//    [_rfBtn addTarget:self action:@selector(webRefreshAction:) forControlEvents:UIControlEventTouchUpInside];
//    [_bar addSubview:_rfBtn];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    _progressView.left = 0;
    _progressView.top = self.navigationController.navigationBar.height;
    _progressView.width = self.view.width;
    _progressView.height = 5;
    
    _webView.left = 0;
    _webView.top = 0;
    _webView.width = self.view.width;
    _webView.height = self.view.height;
    
    _bar.left = 0;
    _bar.bottom = self.view.bottom;
    _bar.width = self.view.width;
    _bar.height = 40;
    
    _bkBtn.width = 40;
    _bkBtn.height = 40;
    _bkBtn.top = 0;
    _bkBtn.right = self.view.width/2 - 20;
    
    _fwBtn.width = 40;
    _fwBtn.height = 40;
    _fwBtn.top = 0;
    _fwBtn.right = self.view.width/2 + 20;
    
//    _rfBtn.width = 40;
//    _rfBtn.height = 40;
//    _rfBtn.top = 0;
//    _rfBtn.right = self.view.width - 20;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Action

- (void)backAction:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)webBackAction:(id)sender{
    if ([_webView canGoBack]) {
        [_webView goBack];
    }
}
- (void)webForwardAction:(id)sender{
    if ([_webView canGoForward]) {
        [_webView goForward];
    }
}

- (void)webRefreshAction:(id)sender{
    [_webView reload];
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        
        if (object == _webView) {
            [_progressView setAlpha:1.0f];
            [_progressView setProgress:_webView.estimatedProgress animated:YES];
            
            if(_webView.estimatedProgress >= 1.0f) {
                
                [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                    [_progressView setAlpha:0.0f];
                } completion:^(BOOL finished) {
                    [_progressView setProgress:0.0f animated:NO];
                }];
                
            }
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
        
    }else if ([keyPath isEqualToString:@"title"]){
        if (object == _webView) {
            self.title = _webView.title;
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"%@ 开始加载...",NSStringFromClass([self class]));
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    NSLog(@"%@ 开始接收",NSStringFromClass([self class]));
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"%@ 加载完成",NSStringFromClass([self class]));
    _bkBtn.enabled = _webView.canGoBack;
    _fwBtn.enabled = _webView.canGoForward;
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"%@ 加载失败 code:%ld",NSStringFromClass([self class]),error.code);
    _bkBtn.enabled = _webView.canGoBack;
    _fwBtn.enabled = _webView.canGoForward;
}
@end
